# -*- coding: UTF-8 -*-
"""
@Time:2022/4/29 9:46
@File:userinfo.py
@Author:常雷
@Software:PyCharm
"""
import datetime
from rest_framework.response import Response
from django.shortcuts import render, HttpResponse
from rest_framework import serializers
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView, ListAPIView, RetrieveAPIView
from palyWordDackend import models
from django.forms import model_to_dict
from rest_framework import status
from django.db.models import F
import uuid
import requests

class UserInfoModelSerializer(serializers.ModelSerializer):
    creat_date = serializers.DateTimeField(format="%Y-%m-%d %H:%M")

    class Meta:
        model = models.UserInfo
        # fields = "__all__"
        exclude = ['password', 'openid']

class CheckUserInfo(APIView):
    pass

class LoginViewModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        exclude = ['password']

class LoginView(APIView):
    def get(self, request, *args, **kwargs):
        import random
        phone = request.query_params.get('phone')

        print(phone)
        code = ''
        n = 4
        while n > 0:
            code += str(random.randint(0, 9))
            n -= 1
        print(code)
        # 随机验证码在登陆的视图函数里面需要用到 要比对 所以要找地方存起来并且其他视图函数也能拿到
        # models.
        request.session['code'] = code
        return Response({'code': code}, status=status.HTTP_200_OK)


    def post(self, request, *args, **kwargs):
        """
        用户登录逻辑
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        print(request.data)
        code = request.data.get('code')
        phone = request.data.get('phone')
        username = request.data.get('username')
        password = request.data.get('password')
        wx_code = request.data.get('wx_code')
        token = str(uuid.uuid4())

        # openid的获取:需要拿着wx_code去微信小程序申请
        # https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html
        # https://api.weixin.qq.com/sns/jscode2session
        info = {
            'appid': "wx88c388ccdb201d33",
            'secret': "d114afa770a3de229c9f002605a4fc1c",
            'js_code': wx_code,
            'grant_type': "authorization_code",
        }
        # 发请求
        result = requests.get(url='https://api.weixin.qq.com/sns/jscode2session', params=info)
        # print(result.json())    # {'session_key': 'uIcuPxk9ezQP8dcDD5U1uw==', 'openid': 'o5_wD46YwLkhMQslTOs8xeqNb1Ag'}
        openid = result.json()['openid']
        # print("request.session['code']",request.session['code'])
        # if phone and request.session['code'] == code:
        data = {}

        print(request.session.get('code'))
        if phone and request.session.get('code') == code:
            exists_1 = models.UserInfo.objects.filter(phone=phone)
            if not exists_1.exists():
                # 不存在创建
                models.UserInfo.objects.create(
                    phone=phone,
                    token=token,
                    openid=openid,
                )
            else:
                # data['username']=exists_1.values('username')
                data.update(list(exists_1.values('username'))[0])
                # 存在更新 openid可以设置,可以不设置
                models.UserInfo.objects.filter(phone=phone).update(token=token, openid=openid)
        elif username and password:
            exists_2 = models.UserInfo.objects.filter(username=username, password=password)
            if not exists_2.exists():
                # 不存在创建
                models.UserInfo.objects.create(
                    username=username,
                    first_name=username,
                    password=password,
                    token=token,
                    openid=openid,
                )
            else:
                # print(exists_2.values('phone'))<QuerySet [{'phone': '18303612276'}]>
                data.update(list(exists_2.values('phone'))[0])
                # data['phone']=exists_2.values('phone')
                # 存在更新 openid可以设置,可以不设置
                models.UserInfo.objects.filter(username=username, password=password,).update(token=token, openid=openid)
        else:
            return Response(status=status.HTTP_201_CREATED)

        data['token']=token
        data['is_active'] = '活跃'
        # data['userId']='666'
        data['avatar'] = models.UserInfo.objects.filter(token=token).values('avatar')[0]['avatar']
        print(data)
        # return Response({['token'] :token})
        return Response(data)
